package com.liuceng.zen.web.controller;

import com.liuceng.zen.Page;
import com.liuceng.zen.mapper.AdDirectedMapper;
import com.liuceng.zen.pojo.domain.*;
import com.liuceng.zen.pojo.form.FrontAdGroupForm;
import com.liuceng.zen.pojo.form.FrontMaterialForm;
import com.liuceng.zen.pojo.form.GroupNotThroughReasonFrom;
import com.liuceng.zen.service.*;
import com.liuceng.zen.web.auth.realm.ShiroDbRealm.UserContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
public class CommonController extends BaseController {
  private final static Logger LOG = LoggerFactory.getLogger(CommonController.class);

  @Autowired
  MemberService memberService;
  @Autowired
  DashboardService dashboardService;
  @Autowired
  DictRegionService dictRegionService;
  @Autowired
  GdtCreativeService gdtCreativeService;
  @Autowired
  FrontMaterialService frontMaterialService;
  @Autowired
  FrontCreativeService frontCreativeService;
  @Autowired
  FrontAdGroupService frontAdGroupService;
  @Autowired
  private AdDirectedService adDirectedService;
  @Autowired
  private AdDirectedMapper adDirectedMapper;
  @Autowired
  private GroupNotThroughReasonService groupNotThroughReasonService;
  @Autowired
  private FrontSelfOperateCreativeService frontSelfOperateCreativeService;
  @Autowired
  private OperatingTrackService operatingTrackService;

  @RequestMapping(value = "/common/creatives/{id}", method = RequestMethod.GET)
  public @ResponseBody Map<String, Object> ajaxCreativesPage(@PathVariable Integer id) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("frontAdGroupId", id);
    FrontAdGroup fdg = frontAdGroupService.find(id);
    List<FrontCreative> frontCreatives = frontCreativeService.findFrontCreatives(map);

    map.put("frontCreatives", frontCreatives);
    map.put("frontAdGroup", fdg);
    return map;
  }

  @RequestMapping(value = "/common/new_creatives/{id}", method = RequestMethod.GET)
  public @ResponseBody List<FrontSelfOperateCreative> ajaxCreatives(@PathVariable Integer id) {
    Map<String,Object> map = new HashMap<>();
    map.put("frontAdGroupId",id);
    map.put("memberId",getCurrentUserId());
    List<FrontSelfOperateCreative> creatives = frontSelfOperateCreativeService.search(map);
    return creatives;
  }

  @RequestMapping(value = "/common/check_creatives/{sitesetType}", method = RequestMethod.GET)
  public String ajaxCreativesPage(@PathVariable Integer sitesetType,
      @ModelAttribute("form") FrontMaterialForm form) {
    form.setMemberId(getCurrentUserId());
    form.setSitesetType(sitesetType);
    form.setPage(frontMaterialService.findPage(form));
    return "ad/creatives";
  }

  @RequestMapping(value = "/common/area/{level}/{id}", method = RequestMethod.GET)
  public @ResponseBody List<DictRegion> getRegions(@PathVariable Integer level,
      @PathVariable Integer id) {
    List<DictRegion> regions = dictRegionService.findRegions(level, id);
    return regions;
  }

  // 获取定向页面
  @RequestMapping(value = "/common/target", method = RequestMethod.GET)
  public String getTarget(@ModelAttribute("form") FrontAdGroupForm form){
    // 定向地区
    List<DictRegion> provinces = dictRegionService.findProvinces();
    form.setProvinces(provinces);
    return "ad/_target";
  }

  // 获取定向页面
  @RequestMapping(value = "/common/target_detail/{id}", method = RequestMethod.GET)
  public String getTargetDetail(@ModelAttribute("form") FrontAdGroupForm form,@PathVariable Integer id){
    // 定向地区
    List<DictRegion> provinces = dictRegionService.findProvinces();
    form.setProvinces(provinces);
    AdDirected adDirected = adDirectedService.find(id);
    form.setAdDirected(adDirected);
    return "ad/_target_detail";
  }

  // 获取定向页面
  @RequestMapping(value = "/common/target/delete/{id}", method = RequestMethod.POST)
  @ResponseBody
  public String deleteTarget(@PathVariable Integer id){
    // 定向地区
    adDirectedService.delete(id);
    return "success";
  }

  //保存定向数据
  @RequestMapping(value = "/common/target", method = RequestMethod.POST)
  @ResponseBody
  public AdDirected saveTarget(@ModelAttribute("form") FrontAdGroupForm form){
    if(form.getAdTargetId().size()>0){
      AdDirected adDirected = adDirectedService.find(form.getAdTargetId().get(0));
      FrontAdGroup frontAdGroup = frontAdGroupService.find(form.getFrontAdGroupId());
      adDirected.setMemberId(getCurrentUserId());
      boolean status = false;
      // 年龄
      if(!adDirected.getAdTargetAge().equals(StringUtils.join(form.getAdTargetAge(), ","))){
        status = true;
      }
      adDirected
              .setAdTargetAge(form.getAdTargetAge() == null ? null : StringUtils.join(form.getAdTargetAge(), ","));
      // 兴趣
      if(!adDirected.getAdTargetBusinessInterest().equals(StringUtils.join(form.getAdTargetBusinessInterest(), ","))){
        status = true;
      }
      adDirected.setAdTargetBusinessInterest(form.getAdTargetBusinessInterest() == null ? null
              : StringUtils.join(form.getAdTargetBusinessInterest(), ","));
      // 价格
      if(!adDirected.getAdTargetDevicePrice().equals(StringUtils.join(form.getAdTargetDevicePrice(), ","))){
        status = true;
      }
      adDirected.setAdTargetDevicePrice(
              form.getAdTargetDevicePrice() == null ? null : StringUtils.join(form.getAdTargetDevicePrice(), ","));
      // 性别
      if(!adDirected.getAdTargetGender().equals(StringUtils.join(form.getAdTargetGender(), ","))){
        status = true;
      }
      adDirected.setAdTargetGender(form.getAdTargetGender());
      //
      if(!adDirected.getAdTargetHumidity().equals(StringUtils.join(form.getAdTargetHumidity(), ","))){
        status = true;
      }
      adDirected.setAdTargetHumidity(
              form.getAdTargetHumidity() == null ? null : StringUtils.join(form.getAdTargetHumidity(), ","));
      // 地区
      if(adDirected.getAdTargetMarketType() != form.getAdTargetMarketType()){
        status = true;
        //地区自定义
        adDirected.setAdTargetMarketArea(
                form.getAdTargetMarketArea() == null ? null : StringUtils.join(form.getAdTargetMarketArea(), ","));
        adDirected.setAdTargetMarketType(form.getAdTargetMarketType());
      }else{
        //地区自定义
        if(form.getAdTargetMarketType()==2){
          if(!adDirected.getAdTargetMarketArea().equals(StringUtils.join(form.getAdTargetMarketArea(), ","))){
            status = true;
          }
          adDirected.setAdTargetMarketArea(
                  form.getAdTargetMarketArea() == null ? null : StringUtils.join(form.getAdTargetMarketArea(), ","));
        }else{
          adDirected.setAdTargetMarketType(form.getAdTargetMarketType());
        }
      }

      // 婚姻
      if(!adDirected.getAdTargetMarriage().equals(StringUtils.join(form.getAdTargetMarriage(), ","))){
        status = true;
      }
      adDirected.setAdTargetMarriage(
              form.getAdTargetMarriage() == null ? null : StringUtils.join(form.getAdTargetMarriage(), ","));
      // 设备
      if(!adDirected.getAdTargetOs().equals(StringUtils.join(form.getAdTargetOs(), ","))){
        status = true;
      }
      adDirected.setAdTargetOs(form.getAdTargetOs() == null ? null : StringUtils.join(form.getAdTargetOs(), ","));
      //
      if(!adDirected.getAdTargetRay().equals(StringUtils.join(form.getAdTargetRay(), ","))){
        status = true;
      }
      adDirected
              .setAdTargetRay(form.getAdTargetRay() == null ? null : StringUtils.join(form.getAdTargetRay(), ","));
      //
      if(!adDirected.getAdTargetTempeture().equals(StringUtils.join(form.getAdTargetTempeture(), ","))){
        status = true;
      }
      adDirected.setAdTargetTempeture(
              form.getAdTargetTempeture() == null ? null : StringUtils.join(form.getAdTargetTempeture(), ","));
      //
      if(!adDirected.getAdTargetWeather().equals(StringUtils.join(form.getAdTargetWeather(), ","))){
        status = true;
      }
      adDirected.setAdTargetWeather(
              form.getAdTargetWeather() == null ? null : StringUtils.join(form.getAdTargetWeather(), ","));
      adDirected.setUpdatedId(getCurrentUserId());
      adDirected.setCreatedId(getCurrentUserId());
      adDirected.setUpdatedAt(new Date());
      adDirectedMapper.updateByPrimaryKey(adDirected);
      if(adDirected.getAdTargetMarketType()==2){
        List<Integer> area = form.getAdTargetMarketArea();
        if(area.size()>0&&area!=null){
          List<String> names = new ArrayList<>();
          for(int i=0;i<area.size();i++){
            DictRegion dictRegion = dictRegionService.find(area.get(i));
            names.add(dictRegion.getName());
          }
          adDirected.setAdTargetMarketArea(StringUtils.join(names, ","));
        }
      }
      if(status&&null!=form.getFrontAdGroupId()){
        //添加修改广告投放时间操作轨迹
        operatingTrackService.addOperatingTrack(getUserContext().getMember(),frontAdGroup.getTitle(),"修改定向",form.getFrontAdGroupId(),null,null,null);
      }
      return adDirected;
    }else{
      AdDirected adDirected = new AdDirected();
      adDirected.setMemberId(getCurrentUserId());
      // 年龄
      adDirected
              .setAdTargetAge(form.getAdTargetAge() == null ? null : StringUtils.join(form.getAdTargetAge(), ","));
      // 兴趣
      adDirected.setAdTargetBusinessInterest(form.getAdTargetBusinessInterest() == null ? null
              : StringUtils.join(form.getAdTargetBusinessInterest(), ","));
      // 价格
      adDirected.setAdTargetDevicePrice(
              form.getAdTargetDevicePrice() == null ? null : StringUtils.join(form.getAdTargetDevicePrice(), ","));
      // 性别
      adDirected.setAdTargetGender(form.getAdTargetGender());
      //
      adDirected.setAdTargetHumidity(
              form.getAdTargetHumidity() == null ? null : StringUtils.join(form.getAdTargetHumidity(), ","));
      // 地区
      adDirected.setAdTargetMarketType(form.getAdTargetMarketType());
      adDirected.setAdTargetMarketArea(
              form.getAdTargetMarketArea() == null ? null : StringUtils.join(form.getAdTargetMarketArea(), ","));
      adDirected.setAdTargetMarketType(form.getAdTargetMarketType());
      // 婚姻
      adDirected.setAdTargetMarriage(
              form.getAdTargetMarriage() == null ? null : StringUtils.join(form.getAdTargetMarriage(), ","));
      // 设备
      adDirected.setAdTargetOs(form.getAdTargetOs() == null ? null : StringUtils.join(form.getAdTargetOs(), ","));
      //
      adDirected
              .setAdTargetRay(form.getAdTargetRay() == null ? null : StringUtils.join(form.getAdTargetRay(), ","));
      //
      adDirected.setAdTargetTempeture(
              form.getAdTargetTempeture() == null ? null : StringUtils.join(form.getAdTargetTempeture(), ","));
      //
      adDirected.setAdTargetWeather(
              form.getAdTargetWeather() == null ? null : StringUtils.join(form.getAdTargetWeather(), ","));
      adDirected.setUpdatedId(getCurrentUserId());
      adDirected.setCreatedId(getCurrentUserId());
      AdDirected news = adDirectedService.save(adDirected);
      if(news.getAdTargetMarketType()==2){
        List<Integer> area = form.getAdTargetMarketArea();
        if(area.size()>0&&area!=null){
          List<String> names = new ArrayList<>();
          for(int i=0;i<area.size();i++){
            DictRegion dictRegion = dictRegionService.find(area.get(i));
            names.add(dictRegion.getName());
          }
          news.setAdTargetMarketArea(StringUtils.join(names, ","));
        }
      }
      return news;
    }
  }

  //查询审核不通过原因的个数
  @RequestMapping(value = "/common/audit/not_through/reason/count", method = RequestMethod.GET)
  @ResponseBody
  public Integer getReasonCount() {
    List<GroupNotThroughReason> reasons = groupNotThroughReasonService.getNeedRead(getCurrentUserId());
    return reasons==null?0:reasons.size();
  }

  // 消息提醒
  // 审核消息,查询所有审核不通过原因
  @RequestMapping(value = "/ci/audit_list", method = RequestMethod.GET)
  public String ciAuditList() {
    return "/ci/audit_list";
  }

  // 消息提醒
  // 审核消息,查询所有审核不通过原因
  @RequestMapping(value = "/common/audit/delete/{id}", method = RequestMethod.POST)
  @ResponseBody
  public String deleteAuditReason(@PathVariable Integer id) {
    groupNotThroughReasonService.delete(id);
    return "success";
  }

  //查询所有审核不通过原因
  @RequestMapping(value = "/ci/audit_list", method = RequestMethod.POST)
  @ResponseBody
  public Object getReason(GroupNotThroughReasonFrom reasonFrom,HttpServletRequest req) {
    // 初始化信息
    reasonFrom.setSortInfo(req);
    reasonFrom.setMemberId(getCurrentUserId());
    Page<GroupNotThroughReason> reasonPage = groupNotThroughReasonService.findPage(reasonFrom);
    //更新为已读状态
    groupNotThroughReasonService.updateReason(getCurrentUserId());

    Map<String, Object> filterMap = new HashMap<String, Object>();
    filterMap.put("sEcho", 0);
    filterMap.put("iTotalRecords", reasonPage.getContent().size());// 实际的行数
    filterMap.put("iTotalDisplayRecords", reasonPage.getTotalCount());// 总行数
    filterMap.put("data", reasonPage.getContent());// 要以JSON格式返回
    return filterMap;
  }

  @RequestMapping(value = "/document", method = RequestMethod.GET)
  public String document() {
    return "/pages/document";
  }

  @RequestMapping(value = "/settings", method = RequestMethod.GET)
  public String settings() {
    return "/pages/settings";
  }

  @RequestMapping(value = "/blank", method = RequestMethod.GET)
  public String blank() {
    return "/pages/blank";
  }


  @RequestMapping(value = "/lockme", method = RequestMethod.GET)
  public String lockme() {
    return "/pages/lockme";
  }

  /**
   * 错误提示
   * 
   * @return
   */
  @RequestMapping(value = "/404", method = RequestMethod.GET)
  public String error404() {
    return "/pages/404";
  }


  @RequestMapping(value = "/505", method = RequestMethod.GET)
  public String error505() {
    return "/pages/505";
  }

  // email唯一验证
  @RequestMapping(value = "/check_email", method = RequestMethod.GET)
  public void username(String email, HttpServletResponse response) {
    UserContext userContext = getUserContext();
    Member member = userContext.getMember();
    Member member2 = memberService.selectByEmail(email);
    if (member2 != null && member2.getId().intValue() != member.getId()) {
      try {
        PrintWriter out = response.getWriter();
        out.write("true");
        out.flush();
        out.close();
      } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        if (LOG.isDebugEnabled()) {
          LOG.debug("检查email是否存在验证失败");
        }
      }
    }
  }
}
